package com.xyhuo.leetcode.december;

/**
 * 搜索旋转排序数组
 * https://leetcode.cn/problems/search-in-rotated-sorted-array/
 *
 * @time 2023/12/13
 */
public class Search {

//    public static void main(String[] args) {
//        Search s = new Search();
//        int[] nums = {6, 0, 1, 2, 3, 4, 5};
//        int[] num1 = {4, 5, 6, 7, 0, 1, 2};
//        int[] num2 = {1};
//        s.search(num2, 1);
//    }

    public int search(int[] nums, int target) {
        int len = nums.length, left = 0, right = len - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                return middle;
            }
            if (nums[left] == target) {
                return left;
            }
            if (nums[right] == target) {
                return right;
            }
            if (nums[left] < nums[middle]) {
                if (target < nums[middle] && target > nums[left]) {
                    right = middle - 1;
                } else {
                    left = middle + 1;
                }
            } else {
                if (target < nums[right] && target > nums[middle]) {
                    left = middle + 1;
                } else {
                    right = middle - 1;
                }
            }
        }
        return -1;
    }
}
